#!/usr/bin/env python
# -* coding: utf-8 -*-

#Author: Gustaw Lewandowski
#Licence : GPL

__author__ = 'Gustaw Lewandowski'

from select import select
import sys
import os
import urwid
from urwid.raw_display import Screen
import editpanel
import dirpanel
import setuppanel
from traceback import format_exc
from ucp import UrwidCmdProc, isUCP
from utils import utilInit, log

MAIN_TITLE = "Urwid Commander 0.1.5"
palette = [("title", "yellow", "dark cyan"),
		("keys", "dark blue", "light gray"),
		("message", "light cyan", "dark green"),
		("linenr", "light blue", "dark cyan"),
		("input", "light gray", "black"),
		("input2", "dark red", "light gray"),
		("focus", "black", "light gray", "bold"),
		("dialog", "black", "light gray", "bold"),
		("file", "light green", "dark blue"),
		("errortxt", "dark red", "dark blue"),
		("selectedfile", "yellow", "dark blue"),
		("selectedfocus", "yellow", "light gray", "bold"),
		("dir", "light gray", "dark blue"),
		("fileedit", "light green", "dark red"),
		('edit', 'yellow', 'dark blue'),
		('body','default', 'default'),
		('foot','dark cyan', 'dark blue', 'bold'),
		('shadow','white','black'),
		('border','black','dark blue'),
		('error','black','dark red'),
		('FxKey','light cyan', 'dark blue', 'underline')]
window = None

class MainWindow(Screen):
	def __init__(self, mode, name=None):
		Screen.__init__(self)
		self.title   = urwid.Text(MAIN_TITLE)
		self.header  = urwid.AttrWrap(self.title, "title")
		self.footer  = urwid.AttrWrap(urwid.Edit(">",''), "input")
		self.body = None
		if mode == 0:
			self.body = urwid.AttrWrap(dirpanel.DirPanel(), 'file')
		elif mode == 1:
			self.body = editpanel.EditPanel(name)
		elif mode == 2:
			self.body = setuppanel.SetupPanel()

		self.view = urwid.Frame(self.body,\
					header = self.header,\
					footer = None)
					#footer=self.footer)

	def update_screen(self, size):
		canvas = self.view.render(size, focus=True)
		self.draw_screen(size, canvas)
		
def unhandled_input(key):
	log.info('unhandled: %s' % repr(key))
	if isUCP(key):
		global window
		ucp = UrwidCmdProc(key, window.view)
	elif not urwid.util.is_mouse_event(key) and key == 'esc':
		raise urwid.ExitMainLoop()

def main():
	utilInit()
	global window
	try:
		if len(sys.argv) == 1:
			window = MainWindow(0)
		elif sys.argv[1] == "-e":
			name = sys.argv[2]
			assert open(name, "a")
			window = MainWindow(1, name)
		elif sys.argv[1] == "-s":
			window = MainWindow(2)
		else:
			raise Exception, "Wrong option"
	except Exception, e:
		log.info(e)
		log.info(format_exc())
		print "\nUsage urwidcmd [-e file.txt]"
		return

	loop = urwid.MainLoop(window.view, palette, unhandled_input=unhandled_input)
	window.start()
        loop.run()
        window.stop()
	log.info("="*15 + " exit " + "="*15)
	return 0

if __name__ == "__main__":
	main()

__all__ = ['main']

